<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>RabbitMQ延迟队列的使用方式 | 飞の博客</title><meta name="author" content="Fei"><meta name="copyright" content="Fei"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="RabbitMQ延迟队列的使用方式，默认延迟实现方案与插件方案">
<meta property="og:type" content="article">
<meta property="og:title" content="RabbitMQ延迟队列的使用方式">
<meta property="og:url" content="https://tengfei2233.gitee.io/2022/10/3/RabbitMQ%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F/index.html">
<meta property="og:site_name" content="飞の博客">
<meta property="og:description" content="RabbitMQ延迟队列的使用方式，默认延迟实现方案与插件方案">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-27/rabbitmq.jpg">
<meta property="article:published_time" content="2022-10-03T06:24:50.000Z">
<meta property="article:modified_time" content="2022-10-03T06:24:50.000Z">
<meta property="article:author" content="Fei">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="rabbitmq">
<meta property="article:tag" content="延迟队列">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-27/rabbitmq.jpg"><link rel="shortcut icon" href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/icon.png"><link rel="canonical" href="https://tengfei2233.gitee.io/2022/10/3/RabbitMQ%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="msvalidate.01" content="2ADFA30867CBC6E090E3C5B244DC311D"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.3.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?07a1f58fb95d3d4a97c2ae0a181c9964";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.staticfile.org/flickr-justified-gallery/2.1.2/fjGallery.min.js',
      css: 'https://cdn.staticfile.org/flickr-justified-gallery/2.1.2/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'RabbitMQ延迟队列的使用方式',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-03 14:24:50'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/fei.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">24</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-27/rabbitmq.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="飞の博客"><span class="site-name">飞の博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">RabbitMQ延迟队列的使用方式</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-10-03T06:24:50.000Z" title="发表于 2022-10-03 14:24:50">2022-10-03</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-10-03T06:24:50.000Z" title="更新于 2022-10-03 14:24:50">2022-10-03</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/rabbitmq/">rabbitmq</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="RabbitMQ延迟队列的使用方式"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="RabbitMQ实现延迟队列"><a href="#RabbitMQ实现延迟队列" class="headerlink" title="RabbitMQ实现延迟队列"></a>RabbitMQ实现延迟队列</h2><h3 id="Rabbit安装方式，以及对应延迟队列插件安装方式：见：Centos7-安装-RabbitMQ-教程"><a href="#Rabbit安装方式，以及对应延迟队列插件安装方式：见：Centos7-安装-RabbitMQ-教程" class="headerlink" title="Rabbit安装方式，以及对应延迟队列插件安装方式：见：Centos7 安装 RabbitMQ 教程 "></a>Rabbit安装方式，以及对应延迟队列插件安装方式：见：<a target="_blank" rel="noopener" href="https://ten-fei.gitee.io/2022/10/2/Centos7%E5%AE%89%E8%A3%85RabbitMQ%E6%95%99%E7%A8%8B/">Centos7 安装 RabbitMQ 教程 </a></h3><h3 id="一、方式一"><a href="#一、方式一" class="headerlink" title="一、方式一"></a>一、方式一</h3><h4 id="1-1-配置常量"><a href="#1-1-配置常量" class="headerlink" title="1.1 配置常量"></a>1.1 配置常量</h4> <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DelayConstant</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 延迟队列 TTL 名称</span></span><br><span class="line"><span class="comment">     * 延迟队列名称</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAY_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;delay.queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 延时队列交换机</span></span><br><span class="line"><span class="comment">     * 延时消息就是发送到该交换机的</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAY_EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;delay.exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 延迟路由键</span></span><br><span class="line"><span class="comment">     * routing key 名称 路由键</span></span><br><span class="line"><span class="comment">     * 具体延时消息发送在该 routingKey 的</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAY_ROUTING_KEY</span> <span class="operator">=</span> <span class="string">&quot;delay.routing_key&quot;</span>;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 死信队列名称</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;dead.queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 死信队列交换机</span></span><br><span class="line"><span class="comment">     * 死信队列交换机 DLX，dead letter发送到的 exchange</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;dead.exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 死信路由键</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_ROUTING_KEY</span> <span class="operator">=</span> <span class="string">&quot;dead.exchange&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>实体类</li>
</ul>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@ApiModel(&quot;订单信息&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Order</span> <span class="keyword">implements</span> <span class="title class_">Serializable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;订单id&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Long orderId;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;订单金额&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Double orderMoney;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;订单信息&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String orderMsg;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;订单状态&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Integer orderStatus;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;延迟执行时间/s&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Integer delayTime;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>* </p>
<h4 id="1-2-队列配置"><a href="#1-2-队列配置" class="headerlink" title="1.2 队列配置"></a>1.2 队列配置</h4> <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DelayRabbitConfig</span> &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1.死信队列</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">orderQueue</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(DelayConstant.DEAD_QUEUE_NAME, <span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 2.死信交换机</span></span><br><span class="line"><span class="comment">     * 通过死信交换机把死信消息发送到指定的队列中去</span></span><br><span class="line"><span class="comment">     * 将路由键和某模式进行匹配。此时队列需要绑定要一个模式上。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> TopicExchange <span class="title function_">orderTopicExchange</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">TopicExchange</span>(DelayConstant.DEAD_EXCHANGE_NAME);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 3.死信队列（绑定交换机）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">orderBinding</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 将死信队列绑定到死信交换机上，通过死信路由键</span></span><br><span class="line"><span class="comment">         * TODO 如果要让延迟队列之间有关联,这里的 routingKey 和 绑定的交换机很关键</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(orderQueue()).to(orderTopicExchange())</span><br><span class="line">            .with(DelayConstant.DEAD_ROUTING_KEY);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 4.延时队列配置</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;</span></span><br><span class="line"><span class="comment">     * 1、第一种方式是直接设置 Queue 延迟时间 但如果直接给队列设置过期时间,这种做法不是很灵活,（当然二者是兼容的,默认是时间小的优先）</span></span><br><span class="line"><span class="comment">     * params.put(&quot;x-message-ttl&quot;, 5 * 1000);</span></span><br><span class="line"><span class="comment">     * 2、第二种就是每次发送消息动态设置延迟时间,这样我们可以灵活控制</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">delayOrderQueue</span><span class="params">()</span> &#123;</span><br><span class="line">        Map&lt;String, Object&gt; params = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        <span class="comment">// x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称，即死信消息转发到那个队列</span></span><br><span class="line">        params.put(<span class="string">&quot;x-dead-letter-exchange&quot;</span>, DelayConstant.DEAD_EXCHANGE_NAME);</span><br><span class="line">        <span class="comment">// x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。</span></span><br><span class="line">        params.put(<span class="string">&quot;x-dead-letter-routing-key&quot;</span>, DelayConstant.DEAD_OUTING_KEY);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(DelayConstant.DELAY_QUEUE, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, params);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 5. 延迟交换机</span></span><br><span class="line"><span class="comment">     * 延时队列绑定到交换机上，要求该消息与一个特定的路由键完全匹配。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> DirectExchange <span class="title function_">orderDelayExchange</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">DirectExchange</span>(DelayConstant.DELAY_EXCHANGE_NAME);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 6.将延迟队列绑定到延迟交换机上，通过延迟路由键</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">dlxBinding</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(delayOrderQueue()).to(orderDelayExchange())</span><br><span class="line">            .with(DelayConstant.DELAY_ROUTING_KEY);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="1-3-生产者，消费者"><a href="#1-3-生产者，消费者" class="headerlink" title="1.3 生产者，消费者"></a>1.3 生产者，消费者</h4>  <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/delayQueue&quot;)</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Api(&quot;无跳过延迟队列&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProductAndConsumer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> order 订单实体信息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Anonymous</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/product&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">product</span><span class="params">(Order order)</span> &#123;</span><br><span class="line">        <span class="comment">/* 确认的回调 确认消息是否到达 Broker 服务器 其实就是是否到达交换器</span></span><br><span class="line"><span class="comment">         * 如果发送时候指定的交换器不存在 ack 就是 false 代表消息不可达</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -&gt; &#123;</span><br><span class="line">            log.info(<span class="string">&quot;correlationData：&#123;&#125; , ack:&#123;&#125;&quot;</span>, correlationData.getId(), ack);</span><br><span class="line">            <span class="keyword">if</span> (!ack) &#123;</span><br><span class="line">                <span class="comment">// TODO 消息不可达的后续操作</span></span><br><span class="line">                System.out.println(<span class="string">&quot;进行对应的消息补偿机制&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">/* 消息失败的回调</span></span><br><span class="line"><span class="comment">         * 例如消息已经到达交换器上，但路由键匹配任何绑定到该交换器的队列，会触发这个回调，此时 replyText: NO_ROUTE</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        rabbitTemplate.setReturnsCallback(returnedMessage -&gt; &#123;</span><br><span class="line">            log.info(<span class="string">&quot;message:&#123;&#125;; replyCode: &#123;&#125;; replyText: &#123;&#125; ; exchange:&#123;&#125; ; routingKey:&#123;&#125;&quot;</span>,</span><br><span class="line">                    returnedMessage.getMessage(), returnedMessage.getReplyCode(), 		                                     returnedMessage.getReplyText(),</span><br><span class="line">                    returnedMessage.getExchange(), returnedMessage.getRoutingKey());</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">// 在实际中ID 应该是全局唯一 能够唯一标识消息 消息不可达的时候触发ConfirmCallback回调方法时可以获取该值，进行对应的错误处理</span></span><br><span class="line">        <span class="type">CorrelationData</span> <span class="variable">correlationData</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">CorrelationData</span>(order.getOrderId().toString());</span><br><span class="line">        rabbitTemplate.convertAndSend(DelayConstant.DELAY_EXCHANGE_NAME,</span><br><span class="line">                                      DelayConstant.DELAY_ROUTING_KEY, order, message -&gt; &#123;</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 如果配置了 params.put(&quot;x-message-ttl&quot;, 60 * 1000 * 30);</span></span><br><span class="line"><span class="comment">             * 那么这一句也可以省略,具体根据业务需要是声明 Queue 的时候就指定好延迟时间还是在发送自己控制时间</span></span><br><span class="line"><span class="comment">             * 这里为了演示设置为 30 s</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            message.getMessageProperties().setExpiration(order.getDelayTime() * <span class="number">1000</span> + <span class="string">&quot;&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> message;</span><br><span class="line">        &#125;, correlationData);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(queues = &#123;DelayConstant.DEAD_QUEUE_NAME&#125;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">consumer</span><span class="params">(Order order, Message message, Channel channel)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;###########################################&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;【orderDelayQueue 监听的消息】 - 【消费时间】 - [&quot;</span></span><br><span class="line">                + <span class="keyword">new</span> <span class="title class_">Date</span>() + <span class="string">&quot;]- 【订单内容】 - [&quot;</span> + order.toString() + <span class="string">&quot;]&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (order.getOrderStatus() == <span class="number">0</span>) &#123;</span><br><span class="line">            order.setOrderStatus(<span class="number">2</span>);</span><br><span class="line">            System.out.println(<span class="string">&quot;【该订单未支付，取消订单】&quot;</span> + order.toString());</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (order.getOrderStatus() == <span class="number">1</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;【该订单已完成支付】&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (order.getOrderStatus() == <span class="number">2</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;【该订单已取消】&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">&quot;###########################################&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h4 id="1-4-缺陷"><a href="#1-4-缺陷" class="headerlink" title="1.4 缺陷"></a>1.4 缺陷</h4><blockquote>
<ul>
<li>对于经典订单系统，用户在下单后30分钟未操作，系统将删除用户下的订单；</li>
<li>此时使用传统的定时任务扫描数据库并更改也可以完成，但并不能达到实时更新，且当数据量非常大的时候，是否损耗性能</li>
<li>使用rabbitmq的延迟队列，用户在下单后将订单数据放入延迟队列，并设置30分钟的延迟，到达时间后该操作放入死信队列</li>
</ul>
</blockquote>
<ul>
<li><p>以上使用rabbitmq存在一个非常大的问题，加入第一个入队列的订单的延时为100s，第二个加入队列的订单的延时为10s，明显第二个加入队列的更先进入死信队列被消费</p>
</li>
<li><p>但rabbitmq的延迟队列必须按加入顺序出队列。显然是不合理的</p>
</li>
</ul>
<h3 id="二、方式二（推荐）"><a href="#二、方式二（推荐）" class="headerlink" title="二、方式二（推荐）"></a>二、方式二（推荐）</h3><h4 id="2-1-配置常量与队列配置"><a href="#2-1-配置常量与队列配置" class="headerlink" title="2.1 配置常量与队列配置"></a>2.1 配置常量与队列配置</h4> <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DelayMessageConfig</span> &#123;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 延迟队列名称</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAY_EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;plugin.delay.exchange&quot;</span>;</span><br><span class="line">	<span class="comment">// 延迟队列交换机</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAY_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;plugin.delay.queue&quot;</span>;</span><br><span class="line">	<span class="comment">// 延迟队列路由键</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAY_ROUTING_KRY</span> <span class="operator">=</span> <span class="string">&quot;plugin.delay.routing_key&quot;</span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 声明一个延迟队列</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="meta">@Bean</span></span><br><span class="line">	Queue <span class="title function_">delayQueue</span><span class="params">()</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> QueueBuilder.durable(DELAY_QUEUE_NAME).build();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 声明一个交换机</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="meta">@Bean</span></span><br><span class="line">	CustomExchange <span class="title function_">delayExchange</span><span class="params">()</span>&#123;</span><br><span class="line">		</span><br><span class="line">		Map&lt;String, Object&gt; args = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">       args.put(<span class="string">&quot;x-delayed-type&quot;</span>, <span class="string">&quot;direct&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">CustomExchange</span>(DELAY_EXCHANGE_NAME, <span class="string">&quot;x-delayed-message&quot;</span>, <span class="literal">true</span>,<span class="literal">false</span>, args);</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 绑定</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> delayQueue</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> delayExchange</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="meta">@Bean</span></span><br><span class="line">	Binding <span class="title function_">queueBinding</span><span class="params">(Queue delayQueue, CustomExchange delayExchange)</span>&#123;</span><br><span class="line">		</span><br><span class="line">	    <span class="keyword">return</span> BindingBuilder.bind(delayQueue).to(delayExchange).with(DELAY_ROUTING_KRY).noargs();</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-2-生成者与消费者"><a href="#2-2-生成者与消费者" class="headerlink" title="2.2 生成者与消费者"></a>2.2 生成者与消费者</h4> <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/delayQueue2&quot;)</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Api(&quot;可跳过延迟队列&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProAndCum</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> order 消息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/product&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">product</span><span class="params">(Order order)</span> &#123;</span><br><span class="line">        <span class="comment">/* 确认的回调 确认消息是否到达 Broker 服务器 其实就是是否到达交换器</span></span><br><span class="line"><span class="comment">         * 如果发送时候指定的交换器不存在 ack 就是 false 代表消息不可达</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -&gt; &#123;</span><br><span class="line">            log.info(<span class="string">&quot;correlationData：&#123;&#125; , ack:&#123;&#125;&quot;</span>, correlationData.getId(), ack);</span><br><span class="line">            <span class="keyword">if</span> (!ack) &#123;</span><br><span class="line">                <span class="comment">// TODO 消息不可达，进行相应的c</span></span><br><span class="line">                System.out.println(<span class="string">&quot;进行对应的消息补偿机制&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">/* 消息失败的回调</span></span><br><span class="line"><span class="comment">         * 例如消息已经到达交换器上，但路由键匹配任何绑定到该交换器的队列，会触发这个回调，此时 replyText: NO_ROUTE</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        rabbitTemplate.setReturnsCallback(returnedMessage -&gt; &#123;</span><br><span class="line">            log.info(<span class="string">&quot;message:&#123;&#125;; replyCode: &#123;&#125;; replyText: &#123;&#125; ; exchange:&#123;&#125; ; routingKey:&#123;&#125;&quot;</span>,</span><br><span class="line">                    returnedMessage.getMessage(), returnedMessage.getReplyCode(), returnedMessage.getReplyText(),</span><br><span class="line">                    returnedMessage.getExchange(), returnedMessage.getRoutingKey());</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">// 在实际中ID 应该是全局唯一 能够唯一标识消息 消息不可达的时候触发ConfirmCallback回调方法时可以获取该值，进行对应的错误处理</span></span><br><span class="line">        <span class="type">CorrelationData</span> <span class="variable">correlationData</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">CorrelationData</span>(order.getOrderId().toString());</span><br><span class="line">        rabbitTemplate.convertAndSend(DelayMessageConfig.DELAY_EXCHANGE_NAME,                                              DelayMessageConfig.ROUTING_KRY</span><br><span class="line">                , order, message -&gt; &#123;</span><br><span class="line">                    <span class="comment">// 设置延迟时间</span></span><br><span class="line">                    message.getMessageProperties().setDelay(order.getDelayTime() * <span class="number">1000</span>);</span><br><span class="line">                    <span class="keyword">return</span> message;</span><br><span class="line">                &#125;, correlationData);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(queues = &#123;DelayMessageConfig.DELAY_QUEUE_NAME&#125;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">consumer</span><span class="params">(Order order, Message message, Channel channel)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;###########################################&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;【orderDelayQueue 监听的消息】 - 【消费时间】 - [&quot;</span></span><br><span class="line">                + <span class="keyword">new</span> <span class="title class_">Date</span>() + <span class="string">&quot;]- 【订单内容】 - [&quot;</span> + order.toString() + <span class="string">&quot;]&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (order.getOrderStatus() == <span class="number">0</span>) &#123;</span><br><span class="line">            order.setOrderStatus(<span class="number">2</span>);</span><br><span class="line">            System.out.println(<span class="string">&quot;【该订单未支付，取消订单】&quot;</span> + order.toString());</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (order.getOrderStatus() == <span class="number">1</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;【该订单已完成支付】&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (order.getOrderStatus() == <span class="number">2</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;【该订单已取消】&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">&quot;###########################################&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-3-注意事项"><a href="#2-3-注意事项" class="headerlink" title="2.3 注意事项"></a>2.3 注意事项</h4><ul>
<li>使用第二种方式需要rabbitmq安装一个延迟队列插件</li>
<li>具体看延迟队列安装：rabbitmq_delayed_message_exchange插件</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://tengfei2233.gitee.io">Fei</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://tengfei2233.gitee.io/2022/10/3/RabbitMQ%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F/">https://tengfei2233.gitee.io/2022/10/3/RabbitMQ%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://tengfei2233.gitee.io" target="_blank">飞の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a><a class="post-meta__tags" href="/tags/rabbitmq/">rabbitmq</a><a class="post-meta__tags" href="/tags/%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97/">延迟队列</a></div><div class="post_share"><div class="social-share" data-image="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-27/rabbitmq.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/wechat.png" target="_blank"><img class="post-qr-code-img" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/alipay.png" target="_blank"><img class="post-qr-code-img" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/10/2/Centos7%E5%AE%89%E8%A3%85RabbitMQ%E6%95%99%E7%A8%8B/" title="Centos7安装RabbitMQ教程"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-27/rabbitmq.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Centos7安装RabbitMQ教程</div></div></a></div><div class="next-post pull-right"><a href="/2022/10/24/DH%E5%AF%86%E9%92%A5%E4%BA%A4%E6%8D%A2%E7%AE%97%E6%B3%95%EF%BC%88%E5%8A%A0%E5%AF%86%E9%80%9A%E4%BF%A1%E5%9F%BA%E7%A1%80%EF%BC%89/" title="DH密钥交换算法（加密通信基础）"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-24/DC-lock.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">DH密钥交换算法（加密通信基础）</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/" title="netty的基本使用，基本原理分析，相关问题解(更新中...)"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-11-21</div><div class="title">netty的基本使用，基本原理分析，相关问题解(更新中...)</div></div></a></div><div><a href="/2023/6/25/Java%E5%8E%9F%E7%94%9FNio%E6%9C%8D%E5%8A%A1%E7%AB%AF%E4%B8%8E%E5%AE%A2%E6%88%B7%E7%AB%AF%E7%BC%96%E5%86%99/" title="Java原生Nio服务端与客户端编写"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-25/Nio.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-06-25</div><div class="title">Java原生Nio服务端与客户端编写</div></div></a></div><div><a href="/2023/6/15/SpringBoot%E9%9B%86%E6%88%90SpringSecurity%E5%AE%9E%E7%8E%B0%E5%89%8D%E5%90%8E%E7%AB%AF%E5%88%86%E7%A6%BB%E6%9D%83%E9%99%90%E6%A0%A1%E9%AA%8C-%E6%96%B0%E7%89%88%E9%85%8D%E7%BD%AE%E6%96%B9%E5%BC%8F/" title="SpringBoot集成SpringSecurity实现前后端分离权限校验(新版配置方式)(待更新...)"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-15/security.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-07-17</div><div class="title">SpringBoot集成SpringSecurity实现前后端分离权限校验(新版配置方式)(待更新...)</div></div></a></div><div><a href="/2023/6/15/Jackson%E8%A7%A3%E5%86%B3SpringMVC%E5%85%A8%E5%B1%80%E5%BA%8F%E5%88%97%E5%8C%96%E8%BF%94%E5%9B%9E%E4%B8%ADLong%E7%B1%BB%E5%9E%8B%E7%B2%BE%E5%BA%A6%E4%B8%A2%E5%A4%B1%E9%97%AE%E9%A2%98/" title="配置SpringMvc全局序列化与反序列化，解决Long类型下精度丢失问题（使用FastJson2）"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-15/js.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-06-19</div><div class="title">配置SpringMvc全局序列化与反序列化，解决Long类型下精度丢失问题（使用FastJson2）</div></div></a></div><div><a href="/2023/3/14/%E6%9E%84%E5%BB%BA%E5%8F%AF%E9%87%8D%E5%A4%8D%E8%AF%BB%E5%8F%96Request-Response/" title="构建可重复读取Request&#x2F;Response"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-3-14/request.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-03-14</div><div class="title">构建可重复读取Request&#x2F;Response</div></div></a></div><div><a href="/2023/3/2/Java%E8%B0%83%E7%94%A8Ffmpeg%E5%AE%9E%E7%8E%B0%E8%A7%86%E9%A2%91%E8%BD%ACM3U8/" title="Java集成Ffmpeg实现视频转M3U8"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-3-2/ffmpeg.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-03-02</div><div class="title">Java集成Ffmpeg实现视频转M3U8</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/fei.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Fei</div><div class="author-info__description">当你想起来了，那就记录一点吧</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">24</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/tengfei2233" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://gitee.com/tengfei2233" target="_blank" title="Gitee"><i class="fab fa-git"></i></a><a class="social-icon" href="/youfeige@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">当你迷茫的时候，那就静下心想想吧！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#RabbitMQ%E5%AE%9E%E7%8E%B0%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97"><span class="toc-number">1.</span> <span class="toc-text">RabbitMQ实现延迟队列</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Rabbit%E5%AE%89%E8%A3%85%E6%96%B9%E5%BC%8F%EF%BC%8C%E4%BB%A5%E5%8F%8A%E5%AF%B9%E5%BA%94%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97%E6%8F%92%E4%BB%B6%E5%AE%89%E8%A3%85%E6%96%B9%E5%BC%8F%EF%BC%9A%E8%A7%81%EF%BC%9ACentos7-%E5%AE%89%E8%A3%85-RabbitMQ-%E6%95%99%E7%A8%8B"><span class="toc-number">1.1.</span> <span class="toc-text">Rabbit安装方式，以及对应延迟队列插件安装方式：见：Centos7 安装 RabbitMQ 教程 </span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E6%96%B9%E5%BC%8F%E4%B8%80"><span class="toc-number">1.2.</span> <span class="toc-text">一、方式一</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-1-%E9%85%8D%E7%BD%AE%E5%B8%B8%E9%87%8F"><span class="toc-number">1.2.1.</span> <span class="toc-text">1.1 配置常量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-%E9%98%9F%E5%88%97%E9%85%8D%E7%BD%AE"><span class="toc-number">1.2.2.</span> <span class="toc-text">1.2 队列配置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-3-%E7%94%9F%E4%BA%A7%E8%80%85%EF%BC%8C%E6%B6%88%E8%B4%B9%E8%80%85"><span class="toc-number">1.2.3.</span> <span class="toc-text">1.3 生产者，消费者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-4-%E7%BC%BA%E9%99%B7"><span class="toc-number">1.2.4.</span> <span class="toc-text">1.4 缺陷</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%88%E6%8E%A8%E8%8D%90%EF%BC%89"><span class="toc-number">1.3.</span> <span class="toc-text">二、方式二（推荐）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1-%E9%85%8D%E7%BD%AE%E5%B8%B8%E9%87%8F%E4%B8%8E%E9%98%9F%E5%88%97%E9%85%8D%E7%BD%AE"><span class="toc-number">1.3.1.</span> <span class="toc-text">2.1 配置常量与队列配置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2-%E7%94%9F%E6%88%90%E8%80%85%E4%B8%8E%E6%B6%88%E8%B4%B9%E8%80%85"><span class="toc-number">1.3.2.</span> <span class="toc-text">2.2 生成者与消费者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-3-%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9"><span class="toc-number">1.3.3.</span> <span class="toc-text">2.3 注意事项</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/" title="netty的基本使用，基本原理分析，相关问题解(更新中...)"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="netty的基本使用，基本原理分析，相关问题解(更新中...)"/></a><div class="content"><a class="title" href="/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/" title="netty的基本使用，基本原理分析，相关问题解(更新中...)">netty的基本使用，基本原理分析，相关问题解(更新中...)</a><time datetime="2023-11-21T09:27:51.000Z" title="发表于 2023-11-21 17:27:51">2023-11-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/10/%E5%9C%A8conda%E7%8E%AF%E5%A2%83%E4%B8%8B%E8%BF%90%E8%A1%8Cstable-diffusion-webui-AI%E7%BB%98%E5%9B%BE/" title="在conda环境下运行stable-diffusion-webui AI绘图"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/ai.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="在conda环境下运行stable-diffusion-webui AI绘图"/></a><div class="content"><a class="title" href="/2023/11/10/%E5%9C%A8conda%E7%8E%AF%E5%A2%83%E4%B8%8B%E8%BF%90%E8%A1%8Cstable-diffusion-webui-AI%E7%BB%98%E5%9B%BE/" title="在conda环境下运行stable-diffusion-webui AI绘图">在conda环境下运行stable-diffusion-webui AI绘图</a><time datetime="2023-11-10T07:30:51.000Z" title="发表于 2023-11-10 15:30:51">2023-11-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/10/%E5%9C%A8Ubuntu20%E4%B8%8A%E5%AE%89%E8%A3%85CUDA-cuDNN-Miniconda%E7%8E%AF%E5%A2%83(%E5%85%B6%E5%AE%83%E7%B3%BB%E7%BB%9F%E5%90%8C%E7%90%86)/" title="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/ai.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)"/></a><div class="content"><a class="title" href="/2023/11/10/%E5%9C%A8Ubuntu20%E4%B8%8A%E5%AE%89%E8%A3%85CUDA-cuDNN-Miniconda%E7%8E%AF%E5%A2%83(%E5%85%B6%E5%AE%83%E7%B3%BB%E7%BB%9F%E5%90%8C%E7%90%86)/" title="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)">在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)</a><time datetime="2023-11-10T07:27:51.000Z" title="发表于 2023-11-10 15:27:51">2023-11-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/8/27/Docker-Compose%E5%AD%A6%E4%B9%A0/" title="Docker Compose学习"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-26/docker.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Docker Compose学习"/></a><div class="content"><a class="title" href="/2023/8/27/Docker-Compose%E5%AD%A6%E4%B9%A0/" title="Docker Compose学习">Docker Compose学习</a><time datetime="2023-08-27T15:34:50.000Z" title="发表于 2023-08-27 23:34:50">2023-08-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/8/27/Dockerfile%E5%AD%A6%E4%B9%A0/" title="Dockerfile学习"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-26/docker.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Dockerfile学习"/></a><div class="content"><a class="title" href="/2023/8/27/Dockerfile%E5%AD%A6%E4%B9%A0/" title="Dockerfile学习">Dockerfile学习</a><time datetime="2023-08-27T15:34:37.000Z" title="发表于 2023-08-27 23:34:37">2023-08-27</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-27/rabbitmq.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2024 By Fei</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">欢迎进入<a href="tengfei2233.gitee.io/">飞の博客</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/utils.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/main.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/tw_cn.min.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.1.1/instantpage.min.js" type="module"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.staticfile.org/pangu/4.0.7/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '0kbeJfFlvhvkYfqMqwwVCx1a-gzGzoHsz',
      appKey: 'rziWUw1MTHMW7d9eeCQzu9HV',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.staticfile.org/valine/1.5.1/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="ribbon" src="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/search/local-search.min.js"></script></div></body></html>